from flask import Blueprint, render_template, redirect, url_for, request
from app.models import User, Setting, Loan, AddressBook
from app.forms import LoginForm, SettingForm, UserEditForm, LoanEditForm
from app.extensions import db
from app.utils import redirect_back
from app.decorators import admin_required
from flask_login import current_user, login_user, login_required, logout_user


admin_bp = Blueprint('admin', __name__)


@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('.index'))
    form = LoginForm()
    if form.validate_on_submit():
        mobile = form.mobile.data
        password = form.password.data
        user = User.query.filter_by(mobile=mobile).first()
        if user and user.is_admin:
            if mobile == user.mobile and user.validate_password(password):
                login_user(user)
                return redirect(url_for('.index'))
    return render_template('login.html', form=form)


@admin_bp.route('/')
@admin_required
def index():
    user_count = User.query.count()
    loan_count = Loan.query.count()
    information = [user_count, loan_count]
    return render_template('index.html', information=information)


@admin_bp.route('/setting', methods=['GET', 'POST'])
@admin_required
def setting():
    form = SettingForm()
    config = Setting.query.first()
    if form.validate_on_submit():
        name = form.name.data
        title = form.title.data
        bank = form.bank.data
        number = form.number.data
        config.name = name
        config.title = title
        config.bank = bank
        config.card_number = number
        db.session.commit()
    form.name.data = config.name
    form.title.data = config.title
    form.bank.data = config.bank
    form.number.data = config.card_number
    return render_template('setting.html', form=form)


@admin_bp.route('/user')
@admin_required
def user_management():
    page = request.args.get('page', 1, type=int)
    pagination = User.query.order_by(User.id).paginate(page, per_page=20)
    users = pagination.items
    return render_template('user.html', users=users, pagination=pagination)


@admin_bp.route('/user/add', methods=['GET', 'POST'])
@admin_required
def user_add():
    form = UserEditForm()
    if form.validate_on_submit():
        user = User(name=form.name.data, mobile=form.mobile.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('.user_management'))
    return render_template('user_edit.html', form=form)


@admin_bp.route('/user/edit/<int:user_id>', methods=['GET', 'POST'])
@admin_required
def user_edit(user_id):
    form = UserEditForm()
    user = User.query.get_or_404(user_id)
    if form.validate_on_submit():
        user.name = form.name.data
        user.mobile = form.mobile.data
        db.session.commit()
        return redirect(url_for('.user_management'))
    form.name.data = user.name
    form.mobile.data = user.mobile
    return render_template('user_edit.html', form=form)


@admin_bp.route('/user/delete/<int:user_id>', methods=['POST'])
@admin_required
def user_delete(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    for loan in user.loans:
        db.session.delete(loan)
    db.session.commit()
    return redirect_back()


@admin_bp.route('/loan')
@admin_required
def loan_management():
    page = request.args.get('page', 1, type=int)
    pagination = Loan.query.order_by(Loan.id).paginate(page, per_page=20)
    loans = pagination.items
    return render_template('loan.html', loans=loans, pagination=pagination)


@admin_bp.route('/loan/add', methods=['GET', 'POST'])
def loan_add():
    form = LoanEditForm()
    if form.validate_on_submit():
        if not current_user.loan:
            count = form.count.data
            status = form.status.data
            user_id = form.user.data
            deadline = form.deadline.data
            loan = Loan(count=count, status=status, user_id=user_id, deadline=deadline)
            db.session.add(loan)
            db.session.commit()
            return redirect(url_for('.loan_management'))
        return redirect(url_for('.loan_management'))
    return render_template('loan_edit.html', form=form)


@admin_bp.route('/loan/<int:loan_id>', methods=['GET', 'POST'])
@admin_required
def loan_edit(loan_id):
    loan = Loan.query.get_or_404(loan_id)
    form = LoanEditForm()
    if form.validate_on_submit():
        loan.count = form.count.data
        loan.deadline = form.deadline.data
        loan.user_id = form.user.data
        loan.status = form.status.data
        db.session.commit()
        return redirect(url_for('.loan_management'))
    form.count.data = loan.count
    form.deadline.data = loan.deadline
    form.user.data = loan.user_id
    form.status.data = loan.status
    return render_template('loan_edit.html', form=form)


@admin_bp.route('/loan/delete/<int:loan_id>', methods=['POST'])
@admin_required
def loan_delete(loan_id):
    loan = Loan.query.get_or_404(loan_id)
    db.session.delete(loan)
    db.session.commit()
    return redirect_back()


@admin_bp.route('/address/<int:user_id>', methods=['GET', 'POST'])
def address_book(user_id):
    user = User.query.get_or_404(user_id)
    page = request.args.get('page', 1, type=int)
    pagination = AddressBook.query.filter_by(pid=user_id).paginate(page, per_page=20)
    addresses = pagination.items
    return render_template('address_book.html', addresses=addresses, user=user, pagination=pagination)


@admin_bp.route('/address/delete/<int:address_id>', methods=['POST'])
def address_delete(address_id):
    address = AddressBook.query.get_or_404(address_id)
    db.session.delete(address)
    db.session.commit()
    return redirect_back()


@admin_bp.route('/logout')
@admin_required
@login_required
def logout():
    logout_user()
    return redirect_back()
